package pl.un4giv3n.mightvsmagic.admin.action;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import pl.un4giv3n.mightvsmagic.action.PersistenceAction;
import pl.un4giv3n.mightvsmagic.entity.BonusType;
import pl.un4giv3n.mightvsmagic.entity.Guardian;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserType;

/**
 * @author andrzejewskia
 * this action adds new items to the bazar
 * this action should be performed by admin ONLY
 */
public class EditGuardianAction extends PersistenceAction {

	private static final long serialVersionUID = 1L;
	
	private Long guardianId;
	private String name;
	private String desc;
	private BonusType bonus;
	
	/**
	 * session user
	 */
	private User user;

	private Guardian guardian;

	/* (non-Javadoc)
	 * @see pl.un4giv3n.mightvsmagic.action.PersistenceAction#execute()
	 */
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if (user == null || user.getUserType() != UserType.ADMIN) {
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		if(guardianId != null){
			guardian = entityManager.find(Guardian.class, guardianId);
		}else{
			guardian = new Guardian();
		}
		guardian.setBonus(bonus);
		guardian.setDescription(desc);
		guardian.setName(name);
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
		if(guardianId != null){
			entityManager.merge(guardian);
		}else{
			entityManager.persist(guardian);
		}
		entityManager.flush();
		transaction.commit();
		entityManager.close();
		return SUCCESS;
	}

	public Long getGuardianId() {
		return guardianId;
	}

	public void setGuardianId(Long guardianId) {
		this.guardianId = guardianId;
	}

	public Long getId(){
		return guardian == null ? null : guardian.getId();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	public BonusType getBonus() {
		return bonus;
	}

	public void setBonus(String bonus) {
		this.bonus = BonusType.valueOf(bonus);
	}

	public Guardian getGuardian() {
		return guardian;
	}

	public void setGuardian(Guardian guardian) {
		this.guardian = guardian;
	}
}
